package lee.lxwei.boot.advice;

import com.alibaba.fastjson.JSON;
import lee.lxwei.boot.dto.BaseRes;
import lee.lxwei.boot.web.TestBaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 对返回报文进行统一处理
 * assignableTypes 属性指定为需要拦截 Controller类
 */
@Slf4j
@ControllerAdvice(assignableTypes = {TestBaseController.class})
public class BaseResResponseAdvice implements ResponseBodyAdvice<BaseRes> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    /**
     * SpringMVC 在将响应实体写入响应流前的动作，只能改变响应的内容，并不能改变响应报文的格式
     *
     * @param baseRes
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public BaseRes beforeBodyWrite(BaseRes baseRes, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info(JSON.toJSONString(baseRes));

        baseRes.setMsg("change msg");

        return baseRes;
    }


}
